<template>
  <!--
    flowEditForm.vue
    费用报销详情编辑表单示例
    包含费用类型、发生日期、金额、描述、凭证上传等表单项
    使用 Element Plus 组件库
  -->
  <div class="flow-edit" style="background: white">
    <!-- 表单区域 -->
    <el-form
      ref="formFlowEditSubmitDetailAIRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      :rules="rules"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <el-row :gutter="16">
        <!-- 费用类型选择 -->
        <el-col :span="24">
          <el-form-item label="费用类型" prop="TestFlowSubmit.testFlowSubmitDetail.expenseType">
            <el-radio-group
              class="input-item"
              v-model="formData.TestFlowSubmit.testFlowSubmitDetail.expenseType"
            >
              <el-radio
                v-for="item in expenseTypeWidgetDropdownList"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 发生日期选择 -->
        <el-col :span="24">
          <el-form-item label="发生日期" prop="TestFlowSubmit.testFlowSubmitDetail.expenseTime">
            <el-date-picker
              class="input-item"
              v-model="formData.TestFlowSubmit.testFlowSubmitDetail.expenseTime"
              type="date"
              placeholder=""
              :clearable="true"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <!-- 金额输入 -->
        <el-col :span="24">
          <el-form-item label="金额" prop="TestFlowSubmit.testFlowSubmitDetail.amount">
            <el-input-number
              class="input-item"
              v-model="formData.TestFlowSubmit.testFlowSubmitDetail.amount"
              placeholder=""
              :clearable="true"
              :step="1"
              :controls="true"
            />
          </el-form-item>
        </el-col>
        <!-- 费用描述输入 -->
        <el-col :span="24">
          <el-form-item label="费用描述" prop="TestFlowSubmit.testFlowSubmitDetail.description">
            <el-input
              class="input-item"
              v-model="formData.TestFlowSubmit.testFlowSubmitDetail.description"
              type="textarea"
              placeholder=""
              :clearable="true"
              :show-word-limit="true"
              maxlength="400"
            />
          </el-form-item>
        </el-col>
        <!-- 报销凭证上传 -->
        <el-col :span="24">
          <el-form-item label="报销凭证" prop="TestFlowSubmit.testFlowSubmitDetail.imageUrl">
            <custom-upload
              v-model="imageUrlWidgetFileList"
              name="uploadFile"
              :size="layoutStore.defaultFormItemSize"
              type="expand"
              :headers="getUploadHeaders"
              :action="getUploadActionUrl('/admin/app/testFlowSubmitDetail/upload')"
              :data="{ fieldName: 'imageUrl', asImage: true }"
              :limit="imageUrlWidgetMaxCount"
              :multiple="false"
              @change="onImageUrlChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部操作按钮 -->
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onSubmit"
        >保存</el-button
      >
    </el-row>
  </div>
</template>

<script lang="ts">
// 组件名称定义
export default {
  name: 'formFlowEditSubmitDetailAI',
};
</script>

<script setup lang="ts">
// ---------------------- 依赖与工具导入 ----------------------
import { DialogProp } from '@/components/Dialog/types';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import {
  treeDataTranslate,
  findItemFromList,
  findTreeNodePath,
  findTreeNode,
  stringCase,
} from '@/common/utils';
import { TestFlowSubmitData } from '@/api/generated/testFlowSubmitController';
import { TestFlowSubmitDetailData } from '@/api/generated/testFlowSubmitDetailController';
import { TestFlowSubmitController, TestFlowSubmitDetailController } from '@/api/generated';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

// 路由、布局、上传、通用方法、字典等 hooks
const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } =
  useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

// ---------------------- 组件属性定义 ----------------------
const props = withDefaults(
  defineProps<{
    saveOnSubmit?: boolean; // 是否保存时提交
    rowData?: ANY_OBJECT; // 编辑时传入的行数据
    dialog?: DialogProp<ANY_OBJECT[]>; // Dialog 回调
  }>(),
  {
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

// ---------------------- 表单数据与类型定义 ----------------------
const formFlowEditSubmitDetailAIRef = ref();
// 表单数据类型
type FormFlowEditSubmitDetailAIData = {
  TestFlowSubmit: TestFlowSubmitData;
};
// 表单数据
const formData = reactive<FormFlowEditSubmitDetailAIData>({
  TestFlowSubmit: {
    // 报销详情数据
    testFlowSubmitDetail: {
      // 主键Id
      id: undefined,
      // 报销单据Id
      submitId: undefined,
      // 费用类型
      expenseType: undefined,
      // 发生日期
      expenseTime: undefined,
      // 金额
      amount: undefined,
      // 报销凭证
      imageUrl: undefined,
      // 费用描述
      description: undefined,
    },
  },
});
// ---------------------- 表单验证规则 ----------------------
const rules = reactive({
  'TestFlowSubmit.testFlowSubmitDetail.amount': [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      type: 'number',
      message: '金额只允许输入数字',
      trigger: 'blur',
      transform: value => Number(value),
    },
    {
      type: 'number',
      min: 0,
      message: '金额必须大于0',
      trigger: 'blur',
      transform: value => Number(value),
    },
  ],
  'TestFlowSubmit.testFlowSubmitDetail.imageUrl': [],
  'TestFlowSubmit.testFlowSubmitDetail.expenseTime': [
    { required: true, message: '请输入发生日期', trigger: 'blur' },
  ],
  'TestFlowSubmit.testFlowSubmitDetail.expenseType': [
    { required: true, message: '请输入费用类型', trigger: 'blur' },
  ],
  'TestFlowSubmit.testFlowSubmitDetail.description': [],
});
const instance = getCurrentInstance();

// 是否为编辑模式
const isEdit = computed(() => {
  return props.rowData != null;
});

// ---------------------- 事件处理 ----------------------
// 取消按钮事件
const onCancel = () => {
  props.dialog?.cancel();
};
// 保存按钮事件
const onSubmit = () => {
  formFlowEditSubmitDetailAIRef.value.validate(valid => {
    if (!valid) return;
    let retFormData = {
      ...formData.TestFlowSubmit.testFlowSubmitDetail,
    };
    // 费用类型字典映射
    retFormData.expenseTypeDictMap = findItemFromList(
      expenseTypeWidgetDropdownList.value,
      retFormData.expenseType,
      'id',
    );
    props.dialog?.submit(retFormData);
  });
};

// ---------------------- 数据加载与初始化 ----------------------
// 初始化页面数据
const loadTestFlowSubmitData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TestFlowSubmit.testFlowSubmitDetail = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id,
    };
    TestFlowSubmitController.view(params)
      .then(res => {
        formData.TestFlowSubmit = { ...res.data };
        resolve();
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 费用类型下拉数据获取函数
 * @returns Promise<ListData<DictData>>
 */
const loadExpenseTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'SubmitDetailType', itemIdType: 'Integer' })
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 费用类型下拉配置与组件
const expenseTypeOptions: DropdownOptions<DictData> = {
  loadData: loadExpenseTypeDropdownList,
  isTree: false,
};
const expenseTypeWidget = useDropdown(expenseTypeOptions);
const { dropdownList: expenseTypeWidgetDropdownList } = expenseTypeWidget;
/**
 * 报销凭证上传文件改变事件
 * @param val 上传文件列表
 */
const onImageUrlChange = val => {
  formData.TestFlowSubmit.testFlowSubmitDetail.imageUrl = fileListToJson(val);
};
// 报销凭证上传文件组件
const imageUrlWidget = useUploadWidget(1);
const { fileList: imageUrlWidgetFileList, maxCount: imageUrlWidgetMaxCount } = imageUrlWidget;
// 上传错误处理
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
// 上传超出限制处理
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
// 刷新表单
const refreshFormFlowEditSubmitDetailAI = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormFlowEditSubmitDetailAI = () => {
  refreshFormFlowEditSubmitDetailAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormFlowEditSubmitDetailAI();
};
// 表单初始化
const formInit = () => {
  loadTestFlowSubmitData()
    .then(res => {
      expenseTypeWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      let imageUrlDownloadParams = {
        id: formData.TestFlowSubmit.testFlowSubmitDetail.id,
        fieldName: 'imageUrl',
        asImage: true,
      };
      imageUrlWidgetFileList.value = parseUploadData(
        formData.TestFlowSubmit.testFlowSubmitDetail.imageUrl,
        imageUrlDownloadParams,
      );
      refreshFormFlowEditSubmitDetailAI();
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};

// ---------------------- 生命周期钩子 ----------------------
onMounted(() => {
  // 初始化页面数据
  formInit();
});
</script>
